package com.mrjy.common.util;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;

/**
 * 字符集转换工具类
 */
public class CharSetUtil {
	/**
	 * iso转utf-8
	 * 注意：tomcat8默认已解决get方式乱码现象，在tomcat7下运行时，get方式的请求需要转码
	 * @param str
	 * @return
	 */
	public static String toUTF8(String str){
		try {
			return new String(str.getBytes("iso-8859-1"),"utf-8");
		} catch (UnsupportedEncodingException e) {			
			e.printStackTrace();
		}
		return str;
	}
	
	/**
     * 替换掉超过3个字节的UTF8字符
     * @param text
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String filterOffUtf8Mb4(String text,String replaceString) throws UnsupportedEncodingException {
        byte[] bytes = text.getBytes("utf-8");
        ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
        int i = 0;
        byte[] space = replaceString.getBytes("utf-8");    // 空格unicode:0x3000; utf-8:11100011 10000000 10000000 
        while (i < bytes.length) {
            short b = bytes[i];
            if (b > 0) {
                buffer.put(bytes[i++]);
                continue;
            }

            b += 256; // 去掉符号位

            if (((b >> 5) ^ 0x6) == 0) {
                buffer.put(bytes, i, 2);
                i += 2;
            } else if (((b >> 4) ^ 0xE) == 0) {
                buffer.put(bytes, i, 3);
                i += 3;
            } else if (((b >> 3) ^ 0x1E) == 0) {
            	buffer.put(space);
                i += 4;
            } else if (((b >> 2) ^ 0x3E) == 0) {
            	buffer.put(space);
                i += 5;
            } else if (((b >> 1) ^ 0x7E) == 0) {
            	buffer.put(space);
                i += 6;
            } else {
                buffer.put(bytes[i++]);
            }
        }
        buffer.flip();
        return new String(buffer.array(), "utf-8");
    }
    /**
     * 
     * @param str 要替换的字符串
     * @param length 字符串长度（大于这个长度就中间进行替换）
     * @param patterm 字符串中间替换的字符串（如 *）
     * @return "银虹**)"
     */
    public static String strToReplace(String str , int length , String patterm ){
    	if(str.length() > length){
			String sss = str.substring(2, str.length()-2);
			return str.replace(sss, patterm);
		}
    	return str ;
	}
	
}
